<template>
  <!--购物车-->
  <div class="container-box">
    <div class="cart-box" v-show="!orderDetailVisible">
      <el-card v-if="!showProductDetail" style="width: 80%">
        <el-row class="flex-center">
          <h3>购物车</h3>
        </el-row>
        <!-- <el-row class="flex-center"><el-button size="middle" style="margin-left: 12px;" type="primary"
          @click="addAddress">新增地址</el-button></el-row> -->
        <el-row>
          <div class="address-container">
            <el-table
              :border="true"
              ref="multipleTable"
              :data="cartList"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column
                align="center"
                label="商品主图"
                prop="pictures"
                width="120"
              >
                <template v-slot="{ row }">
                  <img
                    @click="gotoDetail(row)"
                    :src="JSON.parse(row.pictures)[0]"
                    alt=""
                    style="width: 80px; height: auto; cursor: pointer"
                  />
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="商品名称"
                prop="product_name"
                width="120"
              >
              </el-table-column>
              <el-table-column
                align="center"
                prop="category_name"
                label="商品分类"
                width="120"
              >
              </el-table-column>
              <el-table-column
                align="center"
                prop="product_description"
                label="商品描述"
              >
              </el-table-column>
              <el-table-column
                align="center"
                prop="stock"
                label="库存(件)"
                width="120"
              >
              </el-table-column>

              <el-table-column
                align="center"
                width="160"
                prop="quantity"
                label="商品数量"
              >
                <template v-slot="{ row }">
                  <el-input-number
                    size="mini"
                    @change="handleQuantityChange($event, row)"
                    v-model="row.quantity"
                    :min="1"
                    :max="row.stock"
                    label="购买件数"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="price" label="价格(元)">
              </el-table-column>
              <el-table-column align="center" prop="price" label="金额(元)">
                <template v-slot="{ row }">
                  {{ parseFloat(row.price * row.quantity).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column align="center" width="80" label="操作">
                <template v-slot="{ row }">
                  <!-- <el-link :underline="false" type="primary" @click="edit(row)">编辑</el-link> -->
                  <el-link
                    style="margin-left: 10px"
                    :underline="false"
                    type="danger"
                    @click="deleteCart(row)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
            <div class="total-price">
              <div class="total">
                总价：<span class="price">{{ total }}</span> 元
              </div>
              <el-button type="danger" @click="toBuy">点击购买</el-button>
            </div>
          </div>
        </el-row>
      </el-card>
      <!-- 弹框 -->
      <!-- <AddDialog
    :storeData="storeForm"
    :title="title"
    v-if="addVisible"
    :visible.sync="addVisible"
    @confirm="addStoreConfirm"
  ></AddDialog> -->

      <div v-if="showProductDetail">
        <el-button
          style="margin: 20px"
          type="primary"
          @click="showProductDetail = false"
          >返回</el-button
        >
        <el-row>
          <ProductDetail
            class="product-detail"
            :productInfo="productInfo"
          ></ProductDetail>
        </el-row>
      </div>
    </div>

    <div class="order-detail" v-if="orderDetailVisible">
      <OrderDetail @goback="goback" :cartList="multipleSelection"></OrderDetail>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import { generateTextAvatar } from "@/utils/generateTextAvatar";
// import AddDialog from "./components/AddDialog";
import { getAllCartsByUserId, updateCart, deleteCart } from "@/api/user";
import ProductDetail from "@/views/productDetail/index.vue";
import OrderDetail from "./components/OrderDetail.vue";
export default {
  components: {
    ProductDetail,
    OrderDetail,
  },
  data() {
    return {
      multipleSelection: [],
      total: 0,
      orderDetailVisible: false,
      showProductDetail: false,
      cartList: [],
      addVisible: false,
      title: "新增地址",
      storeForm: {},
    };
  },
  computed: {
    ...mapState("user", ["token"]),
    ...mapGetters(["sidebar", "avatar", "name"]),
  },
  mounted() {
    this.getAllCartsByUserId();
  },
  methods: {
    gotoDetail(row) {
      console.log(row);
      this.showProductDetail = true;
      this.productInfo = row;
    },
    async handleQuantityChange(val, row) {
      const params = {
        cart_id: row.cart_id,
        quantity: +val,
      };
      const res = await updateCart(params);
      if (res.status === 0) {
        this.$message({
          type: "success",
          message: "修改成功",
        });
        this.getAllCartsByUserId();
      } else {
        this.$message.error("修改失败！");
      }
    },
    toBuy() {
      if (this.multipleSelection.length === 0)
        return this.$message.warning("请选择商品");
      this.orderDetailVisible = true;
      console.log(this.multipleSelection);
    },
    async goback() {
      await this.getAllCartsByUserId();

      this.orderDetailVisible = false;
    },

    async changeDefault(row) {
      this.$confirm("确认设置该地址为默认地址吗？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const params = {
            cart_id: row.cart_id,
            user_id: +this.token,
            is_default: 1,
          };
          const res = await updateCart(params);
          if (res.status === 0) {
            this.$message({
              type: "success",
              message: "修改默认地址成功",
            });
            this.getAllCartsByUserId();
          } else {
            this.$message.error("修改失败！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getAllCartsByUserId() {
      if (!this.token) {
        this.$message.warning("请先登录！");
        return this.$router.push("/login");
      }
      const { data: res } = await getAllCartsByUserId(+this.token);

      this.cartList = res || [];
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
      this.total = 0;
      for (let i = 0; i < val.length; i++) {
        this.total += val[i].quantity * val[i].price;
      }
      this.total = parseFloat(this.total).toFixed(2);
    },
    deleteCart(row) {
      this.$confirm("确认删除吗？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteCart(row.cart_id);
          if (res.status === 0) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.getAllCartsByUserId();
          } else {
            this.$message.error("删除失败！");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // addAddress() {
    //   this.title = "新增地址";
    //   this.addVisible = true;
    //   this.storeForm = {};
    // },
    edit(row) {
      this.title = "修改地址";
      this.addVisible = true;
      this.storeForm = row;
    },
    addStoreConfirm() {
      //刷新列表
      this.getAllCartsByUserId();
    },
  },
};
</script>

<style scoped lang="scss">
.cart-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 50px;

  .el-card {
    padding: 20px;

    .flex-center {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
    }
  }
}

.btn-list {
  display: flex;
  justify-content: center;

  .el-button {
    width: 200px;
  }
}

.product-detail {
  background-color: #fff;
}

.total-price {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-right: 20px;

  .total {
    margin-right: 20px;

    .price {
      color: red;
      font-size: 20px;
    }
  }
}
</style>
